<?php

namespace app\api\controller;

use app\common\logic\Data;
use think\facade\Validate;
use think\facade\Db;
use app\lib\Result;
use Yurun\Util\HttpRequest;

class File extends Base
{
  /**
   * 推送服务器列表
   * @Author Qianlong <87498106@qq.com>
   * @PersonSite http://www.21ds.cn/
   */
  public function server_list()
  {
    $rule = [
      'pageNo'  => 'number',
      'pageSize'  => 'number',
    ];
    $data = [
      'pageNo' => input('param.pageNo', 1, 'trim'),
      'title' => input('param.title', '', 'trim'),
      'pageSize' => input('param.pageSize', 15, 'trim'),
    ];
    $validate = Validate::rule($rule);
    $result   = $validate->check($data);
    if (!$result) {
      return Result::Error($validate->getError());
    }
    // 构建查询条件
    $where = [];

    if (!empty($data['title'])) {
      $where[] = ['title|_id', 'like', $data['title']];
    }
    $limit = ($data['pageNo'] - 1) * $data['pageSize'];
    $dataList = Db::connect('mongodb')->name('file_server_list')->field('*')->where($where)->order('create_time', 'desc')->limit($limit, $data['pageSize'])->select()->toArray();
    $totalcount = Db::connect('mongodb')->name('file_server_list')->where($where)->count('id');

    foreach ($dataList as &$vo) {
      $vo['create_time'] = date('Y-m-d H:i:s', $vo['create_time']);
      $vo['platform_title'] = self::getPlatform($vo['platform']);
      $vo['aliyun_is_define_url_bool'] = ($vo['aliyun_is_define_url_bool'] === 1) ? true : false;
      $vo['aliyun_is_internal_upload_bool'] = ($vo['aliyun_is_internal_upload_bool'] === 1) ? true : false;
    }
    $returnData['data'] = $dataList;
    $returnData['totalCount'] = $totalcount;
    $returnData['pageNo'] = (int) $data['pageNo'];
    $returnData['pageSize'] = (int) $data['pageSize'];
    return Result::Success($returnData);
  }
  public function all_server_list()
  {

    $dataList = Db::connect('mongodb')->name('file_server_list')->field('_id,title')->where('status', 1)->order('create_time', 'desc')->select()->toArray();
    return Result::Success($dataList);
  }
  public function all_tpl_list()
  {
    $dataList = Db::connect('mongodb')->name('file_tpl_list')->field('_id,title')->where('status', 1)->order('create_time', 'desc')->select()->toArray();
    return Result::Success($dataList);
  }
  public function tpl_list()
  {
    $rule = [
      'pageNo'  => 'number',
      'pageSize'  => 'number',
    ];
    $data = [
      'pageNo' => input('param.pageNo', 1, 'trim'),
      'title' => input('param.title', '', 'trim'),
      'cate_id' => input('param.cate_id', '', 'trim'),
      'pageSize' => input('param.pageSize', 15, 'trim'),
    ];
    $validate = Validate::rule($rule);
    $result   = $validate->check($data);
    if (!$result) {
      return Result::Error($validate->getError());
    }
    // 构建查询条件
    $where = [];

    if (!empty($data['title'])) {
      $where[] = ['title|_id|aliyun_tpl_code|tencent_tpl_code', 'like', $data['title']];
    }
    if (!empty($data['cate_id'])) {
      $where[] = ['cate_id', '=', $data['cate_id']];
    }
    $limit = ($data['pageNo'] - 1) * $data['pageSize'];
    $dataList = Db::connect('mongodb')->name('file_tpl_list')->field('*')->where($where)->order('create_time', 'desc')->limit($limit, $data['pageSize'])->select()->toArray();
    $totalcount = Db::connect('mongodb')->name('file_tpl_list')->where($where)->count('id');

    $cateList = Db::connect('mongodb')->name('file_cate')->field('_id,title')->select()->toArray();
    $cateListArr = [];
    foreach ($cateList as &$vo) {
      $cateListArr[$vo['_id']] = $vo['title'];
    }

    foreach ($dataList as &$vo) {
      $vo['create_time'] = date('Y-m-d H:i:s', $vo['create_time']);
      $vo['cate_title'] = isset($cateListArr[$vo['cate_id']]) ? $cateListArr[$vo['cate_id']] : '';
    }
    $returnData['data'] = $dataList;
    $returnData['totalCount'] = $totalcount;
    $returnData['pageNo'] = (int) $data['pageNo'];
    $returnData['pageSize'] = (int) $data['pageSize'];
    return Result::Success($returnData);
  }
  public function cate_list()
  {
    $rule = [
      'pageNo'  => 'number',
      'pageSize'  => 'number',
    ];
    $data = [
      'pageNo' => input('param.pageNo', 1, 'trim'),
      'title' => input('param.title', '', 'trim'),
      'pageSize' => input('param.pageSize', 15, 'trim'),
    ];
    $validate = Validate::rule($rule);
    $result   = $validate->check($data);
    if (!$result) {
      return Result::Error($validate->getError());
    }
    // 构建查询条件
    $where = [];

    if (!empty($data['title'])) {
      $where[] = ['title|_id', 'like', $data['title']];
    }
    $limit = ($data['pageNo'] - 1) * $data['pageSize'];
    $dataList = Db::connect('mongodb')->name('file_cate')->field('*')->where($where)->order('create_time', 'desc')->limit($limit, $data['pageSize'])->select()->toArray();
    $totalcount = Db::connect('mongodb')->name('file_cate')->where($where)->count('id');

    foreach ($dataList as &$vo) {
      $vo['create_time'] = date('Y-m-d H:i:s', $vo['create_time']);
    }
    $returnData['data'] = $dataList;
    $returnData['totalCount'] = $totalcount;
    $returnData['pageNo'] = (int) $data['pageNo'];
    $returnData['pageSize'] = (int) $data['pageSize'];
    return Result::Success($returnData);
  }
  public function all_cate_list()
  {
    $selectResult = Db::connect('mongodb')->name('file_cate')->field('_id,title')->order('sort', 'desc')->select()->toArray();
    return Result::Success($selectResult);
  }
  public function file_list()
  {
    $rule = [
      'pageNo'  => 'number',
      'pageSize'  => 'number',
      'send_time_ranges|上传时间'  => 'require',
    ];
    $data = [
      'pageNo' => input('param.pageNo', 1, 'trim'),
      'title' => input('param.title', '', 'trim'),
      'fs_id' => input('param.fs_id', '', 'trim'),
      'fc_id' => input('param.fc_id', '', 'trim'),
      'send_time_ranges' => input('param.send_time_ranges/a', '', 'trim'),
      'pageSize' => input('param.pageSize', 50, 'trim'),
    ];
    $validate = Validate::rule($rule);
    $result   = $validate->check($data);
    if (!$result) {
      return Result::Error($validate->getError());
    }
    // 构建查询条件
    $where = [];

    if (!empty($data['title'])) {
      $where[] = ['title|_id', 'like', $data['title']];
    }
    if (!empty($data['fs_id'])) {
      $where[] = ['fs_id', '=', $data['fs_id']];
    }
    if (!empty($data['fc_id'])) {
      $where[] = ['fc_id', '=', $data['fc_id']];
    }
    $start_time = strtotime($data['send_time_ranges'][0]);
    $end_time = strtotime($data['send_time_ranges'][1]);
    if ($end_time - $start_time > 86400 * 90) {
      return Result::Error('时间跨度不能大于90天');
    }
    $limit = ($data['pageNo'] - 1) * $data['pageSize'];
    if (!empty($data['title'])) {
      $dataList = Db::connect('mongodb')->name('file_list')->field('_id,name,url,fs_id,platform,create_time,size_mb,size_kb,ext,fc_id')->where($where)->order('create_time', 'desc')->limit($limit, $data['pageSize'])->select()->toArray();
      $totalcount = Db::connect('mongodb')->name('file_list')->where($where)->count('_id');
    } else {
      $dataList = Db::connect('mongodb')->name('file_list')->field('_id,name,url,fs_id,platform,create_time,size_mb,size_kb,ext,fc_id')->where($where)->whereBetweenTime('create_time', $start_time, $end_time)->order('create_time', 'desc')->limit($limit, $data['pageSize'])->select()->toArray();
      $totalcount = Db::connect('mongodb')->name('file_list')->where($where)->whereBetweenTime('create_time', $start_time, $end_time)->count('_id');
    }

    $serverList = Db::connect('mongodb')->name('file_server_list')->field('_id,title')->select()->toArray();
    $serverListArr = [];
    foreach ($serverList as &$vo) {
      $serverListArr[$vo['_id']] = $vo['title'];
    }
    $cateList = Db::connect('mongodb')->name('file_cate')->field('_id,title')->order('sort', 'desc')->select()->toArray();
    $cateListArr = [];
    foreach ($cateList as &$vo) {
      $cateListArr[$vo['_id']] = $vo['title'];
    }
    $imageFormat = ['bmp', 'webp', 'gif', 'jpg', 'jpeg', 'png'];
    $officeFormat = ['doc', 'docx', 'xls', 'xlsx', 'ppt', 'pptx'];
    foreach ($dataList as &$vo) {
      $vo['create_time'] = date('Y-m-d H:i:s', $vo['create_time']);
      $vo['fs_title'] = isset($serverListArr[$vo['fs_id']]) ? $serverListArr[$vo['fs_id']] : '';
      $vo['fc_title'] = isset($cateListArr[$vo['fc_id']]) ? $cateListArr[$vo['fc_id']] : '';
      $vo['platform_title'] = self::getPlatform($vo['platform']);
      $vo['platform_icon_url'] = '';
      $vo['platform_icon_url'] = 'https://img.alicdn.com/imgextra/i1/573804794/O1CN01uDJDUX1lHhYi5u2Lj_!!573804794.png';
      switch ($vo['platform']) {
        case 'aliyun_oss':
          $vo['platform_icon_url'] = 'https://img.alicdn.com/imgextra/i1/573804794/O1CN01UVljC51lHhYKd3ABf_!!573804794.png';
          break;
        case 'tencent_cos':
          $vo['platform_icon_url'] = 'https://img.alicdn.com/imgextra/i1/573804794/O1CN01SAt1ML1lHhYJwRtPZ_!!573804794.png';
          break;
        case 'qiniu':
          $vo['platform_icon_url'] = 'https://img.alicdn.com/imgextra/i3/573804794/O1CN01IPFuWG1lHhYZg9Qi7_!!573804794.png';
          break;
      }
      $vo['icon_url'] = 'https://img.alicdn.com/imgextra/i2/573804794/O1CN01QTCa5O1lHhYLpaQvA_!!573804794.png';
      $vo['file_type'] = 'file';
      if (in_array($vo['ext'], $imageFormat)) {
        $vo['icon_url'] = $vo['url'];
        $vo['file_type'] = 'img';
      } elseif (in_array($vo['ext'], $officeFormat)) {
        switch ($vo['ext']) {
          case 'xls':
          case 'xlsx':
            $vo['icon_url'] = 'https://img.alicdn.com/imgextra/i3/573804794/O1CN019j1hn71lHhYCa1W23_!!573804794.png';
            break;
          case 'doc':
          case 'docx':
            $vo['icon_url'] = 'https://img.alicdn.com/imgextra/i1/573804794/O1CN01tfcCS01lHhYH1Jyqw_!!573804794.png';
            break;
          case 'ppt':
          case 'pptx':
            $vo['icon_url'] = 'https://img.alicdn.com/imgextra/i2/573804794/O1CN01Jjq0dM1lHhYFSGNQf_!!573804794.png';
            break;
        }
        $vo['file_type'] = 'office';
      } elseif (in_array($vo['ext'], ['pdf', 'mp3', 'wav'])) {
        switch ($vo['ext']) {
          case 'pdf':
            $vo['icon_url'] = 'https://img.alicdn.com/imgextra/i2/573804794/O1CN01220X0A1lHhYK5xP2y_!!573804794.png';
            break;
          case 'mp3':
          case 'wav':
            $vo['icon_url'] = 'https://img.alicdn.com/imgextra/i2/573804794/O1CN01hOJ4JQ1lHhYlN9Pr9_!!573804794.png';
            break;
        }
        $vo['file_type'] = 'iframe';
      } else {
        switch ($vo['ext']) {
          case 'psd':
            $vo['icon_url'] = 'https://img.alicdn.com/imgextra/i4/573804794/O1CN01OAhD4E1lHhYHPxcpx_!!573804794.png';
            break;
          case 'md':
            $vo['icon_url'] = 'https://img.alicdn.com/imgextra/i3/573804794/O1CN01bgZIMP1lHhYLq3uDS_!!573804794.png';
            break;
          case 'zip':
          case 'gz':
          case 'tar.gz':
          case 'rar':
          case '7z':
            $vo['icon_url'] = 'https://img.alicdn.com/imgextra/i3/573804794/O1CN01fh3qVr1lHhZUhBCVE_!!573804794.png';
            break;
          case 'css':
          case 'js':
          case 'java':
          case 'php':
          case 'html':
            $vo['icon_url'] = 'https://img.alicdn.com/imgextra/i2/573804794/O1CN01bgQhr21lHhYHQ9RQG_!!573804794.png';
            break;
        }
      }
    }
    $returnData['data'] = $dataList;
    $returnData['totalCount'] = $totalcount;
    $returnData['pageNo'] = (int) $data['pageNo'];
    $returnData['pageSize'] = (int) $data['pageSize'];
    return Result::Success($returnData);
  }
  public function send_setting()
  {
    if (request()->isPost()) {
      $rule = [
        'ip_limit|来路IP限制'  => 'number',
        'minute_limit|每分钟内发送上限'  => 'number',
        'hour_limit|每小时内发送上限'  => 'number',
        'day_limit|每个自然日内发送上限'  => 'number',
      ];
      $data = [
        'ip_limit' => input('param.ip_limit', '', 'trim'),
        'server_ip' => input('param.server_ip/a', '', 'trim'),
        'minute_limit' => input('param.minute_limit', '', 'trim'),
        'hour_limit' => input('param.hour_limit', '', 'trim'),
        'day_limit' => input('param.day_limit', '', 'trim'),
      ];
      $validate = Validate::rule($rule);
      $result   = $validate->check($data);
      if (!$result) {
        return json(['code' => -1, 'data' => '', 'msg' => $validate->getError()]);
      }
      $data['ip_limit'] = intval($data['ip_limit']);
      $data['minute_limit'] = intval($data['minute_limit']);
      $data['hour_limit'] = intval($data['hour_limit']);
      $data['day_limit'] = intval($data['day_limit']);
      $data['server_ip'] = (empty($data['server_ip'])) ? '' : implode(',', $data['server_ip']);
      $hasSetting = Db::connect('mongodb')->name('send_file_setting')->find();
      if (empty($hasSetting)) {
        unset($data['id']);
        $data['create_time'] = time();
        $data['uid'] = $this->uid;
        $data['username'] = $this->username;
        $data['_id'] = createId();
        Db::connect('mongodb')->name('send_file_setting')->insert($data);
      } else {
        $this->redis->del('dever:file:setting:' . $this->uid, 'full');
        Db::connect('mongodb')->name('send_file_setting')->update($data);
      }
      return Result::Success('', '设置成功');
    } else {
      $infoData = Db::connect('mongodb')->name('send_file_setting')->find();
      $infoData['server_ip'] = explode(',', $infoData['server_ip']);
      return json(['code' => 200, 'data' => $infoData, 'msg' => '获取成功']);
    }
  }
  /**
   * 编辑服务器信息
   * @Author Qianlong <87498106@qq.com>
   * @PersonSite http://www.21ds.cn/
   */
  public function edit_server_info()
  {
    if (request()->isPost()) {
      $rule = [
        'title|标题'  => 'max:128',
        'platform|推送平台'  => 'require',
        'status|配置状态'  => 'require',
        'server_secret|SecretKey'  => 'require',
      ];
      $data = [
        'id' => input('param._id', '', 'trim'),
        'platform' => input('param.platform', '', 'trim'),
        'server_secret' => input('param.server_secret', '', 'trim'),
        'aliyun_is_internal_upload_bool' => input('param.aliyun_is_internal_upload_bool', '', 'trim'),
        'status' => input('param.status', '', 'trim'),
        'title' => input('param.title', '', 'trim'),
        'close_msg' => input('param.close_msg', '', 'trim'),
        'aliyun_is_define_url_bool' => input('param.aliyun_is_define_url_bool', '', 'trim'),
        'aliyun_region' => input('param.aliyun_region', '', 'trim'),
        'aliyun_web_url' => input('param.aliyun_web_url', '', 'trim'),
        'aliyun_bucket' => input('param.aliyun_bucket', '', 'trim'),
        'aliyun_key_secret' => input('param.aliyun_key_secret', '', 'trim'),
        'aliyun_key_id' => input('param.aliyun_key_id', '', 'trim'),
        'aliyun_alc' => input('param.aliyun_alc', '', 'trim'),
        'tenc_bucket' => input('param.tenc_bucket', '', 'trim'),
        'tenc_secret_id' => input('param.tenc_secret_id', '', 'trim'),
        'tenc_secret_key' => input('param.tenc_secret_key', '', 'trim'),
        'tenc_region' => input('param.tenc_region', '', 'trim'),
        'tenc_alc' => input('param.tenc_alc', '', 'trim'),
        'tenc_is_define_url_bool' => input('param.tenc_is_define_url_bool', '', 'trim'),
        'tenc_web_url' => input('param.tenc_web_url', '', 'trim'),
        'qiniu_bucket' => input('param.qiniu_bucket', '', 'trim'),
        'qiniu_region' => input('param.qiniu_region', '', 'trim'),
        'qiniu_sk' => input('param.qiniu_sk', '', 'trim'),
        'qiniu_ak' => input('param.qiniu_ak', '', 'trim'),
        'qiniu_url' => input('param.qiniu_url', '', 'trim'),
        'ak_from' => input('param.ak_from', '', 'trim'),
        'ak_id' => input('param.ak_id', '', 'trim'),
        'aliyun_stylename' => input('param.aliyun_stylename', '', 'trim'),
      ];
      $validate = Validate::rule($rule);
      $result   = $validate->check($data);
      if (!$result) {
        return json(['code' => -1, 'data' => '', 'msg' => $validate->getError()]);
      }
      $limitCount = Db::connect('mongodb')->name('file_server_list')->count();
      $this->security::checkVersionLimit($this->user['version'], 'file_server_num', '文件存储配置数量', $limitCount);
      $data['tenc_is_define_url_bool'] = ($data['tenc_is_define_url_bool'] === 'true' || $data['tenc_is_define_url_bool'] === true) ? 1 : 0;
      $data['aliyun_is_define_url_bool'] = ($data['aliyun_is_define_url_bool'] === 'true' || $data['aliyun_is_define_url_bool'] === true) ? 1 : 0;
      $data['aliyun_is_internal_upload_bool'] = ($data['aliyun_is_internal_upload_bool'] === 'true' || $data['aliyun_is_internal_upload_bool'] === true) ? 1 : 0;
      $data['status'] = intval($data['status']);
      $this->redis->del('dever:file:server:' . $data['id'], 'full');
      if (!empty($data['id'])) {
        $status = Db::connect('mongodb')->name('file_server_list')->where('_id', $data['id'])->update($data);
        $tag = '编辑';
      } else {
        unset($data['id']);
        $data['create_time'] = time();
        $data['uid'] = $this->uid;
        $data['username'] = $this->username;
        $data['_id'] = createId('FS');
        $status = Db::connect('mongodb')->name('file_server_list')->insert($data);
        $tag = '新增';
      }
      if ($status > 0) {
        return json(['code' => 200, 'data' => '', 'msg' => $tag . '成功']);
      } else {
        return json(['code' => -1, 'data' => '', 'msg' => $tag . '失败，请重试']);
      }
    } else {
      $id = input('param.id', '', 'trim');
      if (!$id) {
        return json(['code' => 200, 'data' => [], 'msg' => 'success']);
      }
      $data = Db::connect('mongodb')->name('file_server_list')->where('_id', $id)->find();
      unset($data['smtp_password']);
      return json(['code' => 200, 'data' => $data, 'msg' => 'success']);
    }
  }
  public function edit_cate_info()
  {
    if (request()->isPost()) {
      $rule = [
        'title|标题'  => 'require|max:128',
        'status|状态'  => 'require',
      ];
      $data = [
        'id' => input('param._id', '', 'trim'),
        'title' => input('param.title', '', 'trim'),
        'tag' => input('param.tag', '', 'trim'),
        'status' => input('param.status', '', 'trim'),
      ];
      $validate = Validate::rule($rule);
      $result   = $validate->check($data);
      if (!$result) {
        return json(['code' => -1, 'data' => '', 'msg' => $validate->getError()]);
      }
      $data['status'] = intval($data['status']);
      if (!empty($data['id'])) {
        $status = Db::connect('mongodb')->name('file_cate')->where('_id', $data['id'])->update($data);
        $tag = '编辑';
      } else {
        unset($data['id']);
        $data['create_time'] = time();
        $data['uid'] = $this->uid;
        $data['username'] = $this->username;
        $data['_id'] = createId('FC');
        $status = Db::connect('mongodb')->name('file_cate')->insert($data);
        $tag = '新增';
      }
      if ($status > 0) {
        return json(['code' => 200, 'data' => '', 'msg' => $tag . '成功']);
      } else {
        return json(['code' => -1, 'data' => '', 'msg' => $tag . '失败，请重试']);
      }
    } else {
      $id = input('param.id', '', 'trim');
      if (!$id) {
        return json(['code' => 200, 'data' => [], 'msg' => 'success']);
      }
      $data = Db::connect('mongodb')->name('file_cate')->where('_id', $id)->find();
      unset($data['uid']);
      return json(['code' => 200, 'data' => $data, 'msg' => 'success']);
    }
  }
  public function del_server()
  {
    $rule = [
      'id'  => 'require',
    ];
    $data = [
      'id' => input('param.id', '', 'trim'),
    ];
    $validate = Validate::rule($rule);
    $result   = $validate->check($data);
    if (!$result) {
      return json(['code' => -1, 'data' => '', 'msg' => $validate->getError()]);
    }
    $status = Db::connect('mongodb')->name('file_server_list')->where('_id', $data['id'])->delete();
    if ($status > 0) {
      return json(['code' => 200, 'data' => '', 'msg' => '删除成功']);
    } else {
      return json(['code' => -1, 'data' => '', 'msg' => '删除失败，请稍后重试']);
    }
  }
  public function del_cate()
  {
    $rule = [
      'id'  => 'require',
    ];
    $data = [
      'id' => input('param.id', '', 'trim'),
    ];
    $validate = Validate::rule($rule);
    $result   = $validate->check($data);
    if (!$result) {
      return json(['code' => -1, 'data' => '', 'msg' => $validate->getError()]);
    }
    $hasTpl = Db::connect('mongodb')->name('file_tpl_list')->where('cate_id', $data['id'])->find();
    if (!empty($hasTpl)) {
      return Result::Error('该分类下存在推送模板，不允许删除');
    }
    $status = Db::connect('mongodb')->name('file_cate')->where('_id', $data['id'])->delete();
    if ($status > 0) {
      return json(['code' => 200, 'data' => '', 'msg' => '删除成功']);
    } else {
      return json(['code' => -1, 'data' => '', 'msg' => '删除失败，请稍后重试']);
    }
  }
  public function del_file_batch()
  {
    $rule = [
      'ids'  => 'require',
    ];
    $data = [
      'ids' => input('param.ids/a', '', 'trim'),
    ];
    $validate = Validate::rule($rule);
    $result   = $validate->check($data);
    if (!$result) {
      return json(['code' => -1, 'data' => '', 'msg' => $validate->getError()]);
    }
    $fileInfo = Db::connect('mongodb')->name('file_list')->whereIn('_id', $data['ids'])->select();
    if (empty($fileInfo)) {
      return Result::Error('文件不存在或已删除');
    }
    $fileList = [];
    $userId = [];
    foreach ($fileInfo as $key => $vo) {
      $fileList[$vo['fs_id']][] = $vo['_id'];
      $userId[$vo['fs_id']] = $vo['uid'];
    }
    $result = [];
    $http = new \Yurun\Util\HttpRequest();
    foreach ($fileList as $key => $vo) {
      $reqStatus = deleteFile($vo, $key, $userId[$key], $http);
      if ($reqStatus['code'] == 200) {
        if (!in_array(true, $result)) {
          $result[] = true;
        }
      } else {
        if (!in_array(false, $result)) {
          $result[] = false;
        }
      }
    }
    if (count($result) == 1 && $result[0] == true) {
      return json(['code' => 200, 'data' => '', 'msg' => '删除成功']);
    } else if (count($result) == 2) {
      return json(['code' => -1, 'data' => '', 'msg' => '部分删除成功']);
    } else {
      return json(['code' => -1, 'data' => '', 'msg' => '删除失败']);
    }
  }
  public function all_data()
  {
    $return['date'] = date('Y-m-d H:i:s', strtotime(date('Y-m-d')) - 1);
    $rule = [
      'date_num'  => 'require',
      'date_range'  => 'require',
    ];
    $data = [
      'date_num' => input('param.date_num', '', 'trim'),
      'date_range' => input('param.date_range_format/a', '', 'trim'),
      '_id' => input('param._id', '', 'trim'),
    ];
    $validate = Validate::rule($rule);
    $result   = $validate->check($data);
    if (!$result) {
      return Result::Error($validate->getError());
    }
    $whereTj[] = ['uid', '=', $this->uid];
    if (!empty($data['_id'])) {
      $whereTj[] = ['a_id', '=', $data['_id']];
    }
    $start_date = strtotime($data['date_range'][0]);
    $end_date = strtotime($data['date_range'][1]);

    if ($end_date == $start_date) {
      $cycle_type = 'hour';
      $cycle_num = 24;
    } else {
      $cycle_type = 'day';
      $cycle_num = ($end_date - $start_date) / 86400;
    }
    $end_date = $end_date + 86399;
    if ($end_date - $start_date > 86400 * 90) {
      return Result::Error('时间跨度不能大于90天');
    }
    $whereTj[] = ['hour_stamp', 'between', [$start_date, $end_date]];
    $yestData = Db::connect('mongodb')->name('file_list_tj')->where($whereTj)->select();
    if (!empty($yestData)) {
      $yestData = $yestData->toArray();
    }
    $serialData = [];
    for ($i = 0; $i < $cycle_num; $i++) {
      if ($cycle_type == 'hour') {
        $nowTime = $start_date + $i * 3600;
        $serialData[date('H', $nowTime) . ':00'] = [];
      } else {
        $nowTime = $start_date + $i * 86400;
        $serialData[date('Ymd', $nowTime)] = [];
      }
    }
    if ($cycle_type == 'day') {
      $serialData[date('Ymd', $end_date)] = [];
    }
    foreach ($yestData as $key => $vo) {
      if ($cycle_type == 'hour') {
        $serialData[$vo['only_hour']][] = $vo;
      } else {
        $serialData[$vo['date']][] = $vo;
      }
    }
    $chartData = [];
    $return['total']['rv'] = 0;
    $return['total']['sv'] = 0;
    $num_type = '总数';
    if (!empty($data['_id'])) {
      $num_type = '数';
    }
    foreach ($serialData as $key => $vo) {
      // 日
      if (strlen($key) == 8) {
        if (!isset($vo['sv'])) {
          $vo['sv'] = 0;
        }
        if (!isset($vo['rv'])) {
          $vo['rv'] = 0;
        }
        foreach ($vo as $key2 => $vo2) {
          if (!empty($vo2)) {
            $vo['sv'] = $vo['sv'] + $vo2['sv'];
            $vo['rv'] = $vo['rv'] + $vo2['rv'];
            $return['total']['rv'] = $return['total']['rv'] + $vo2['rv'];
            $return['total']['sv'] = $return['total']['sv'] + $vo2['sv'];
          }
        }
        $year = substr($key, 0, 4);
        $month = substr($key, 4, 2);
        $day = substr($key, -2, 2);
        $charItem['date'] = $year . '-' . $month . '-' . $day;
        $charItem['value'] = $vo['sv'];
        $charItem['category'] = '推送发送' . $num_type;
        $chartData[] = $charItem;
        $charItem['value'] = $vo['rv'];
        $charItem['category'] = '推送阅读' . $num_type;
        $chartData[] = $charItem;
      } else {
        // 时
        if (!isset($vo['sv'])) {
          $vo['sv'] = 0;
        }
        if (!isset($vo['rv'])) {
          $vo['rv'] = 0;
        }
        foreach ($vo as $key2 => $vo2) {
          if (!empty($vo2)) {
            $vo['rv'] = $vo['rv'] + $vo2['rv'];
            $vo['sv'] = $vo['sv'] + $vo2['sv'];
          }
        }
        $charItem['date'] = $key;
        $charItem['value'] = $vo['sv'];
        $charItem['category'] = '推送发送' . $num_type;
        $chartData[] = $charItem;
        $charItem['value'] = $vo['rv'];
        $charItem['category'] = '推送阅读' . $num_type;
        $chartData[] = $charItem;
        $return['total']['sv'] = $return['total']['sv'] + $vo['sv'];
        $return['total']['rv'] = $return['total']['rv'] + $vo['rv'];
        $chartData[] = $charItem;
      }
    }
    $return['total']['rv_sv_rate'] = round($return['total']['rv'] / $return['total']['sv'] * 100, 2);
    $return['chart'] = $chartData;
    return Result::Success($return);
  }
  public function all_file_data()
  {
    $rule = [
      'date_num'  => 'require',
      'date_range'  => 'require',
    ];
    $data = [
      'date_num' => input('param.date_num', '', 'trim'),
      'from_type' => input('param.from_type', '', 'trim'),
      'date_range' => input('param.date_range_format/a', '', 'trim'),
      'fs_id' => input('param.fs_id', '', 'trim'),
      'cid' => input('param.cid', '', 'trim'),
      'pageNo' => input('param.pageNo', 1, 'trim'),
      'pageSize' => input('param.pageSize', 15, 'trim'),
    ];
    $validate = Validate::rule($rule);
    $result   = $validate->check($data);
    if (!$result) {
      return Result::Error($validate->getError());
    }

    $start_date = strtotime($data['date_range'][0]);
    $end_date = strtotime($data['date_range'][1]);

    $end_date = $end_date + 86399;
    if ($end_date - $start_date > 86400 * 90) {
      return Result::Error('时间跨度不能大于90天');
    }
    $where['hour_stamp'] = ['$gte' => $start_date, '$lte' => $end_date];
    $skip = ($data['pageNo'] - 1) * $data['pageSize'];

    $where['uid'] = $this->uid;
    $where['send_result'] = true;
    if (!empty($data['fs_id'])) {
      $where['fs_id'] = $data['fs_id'];
    }
    $whereTj[] = ['uid', '=', $this->uid];
    $whereTj[] = ['send_result', '=', true];
    if (!empty($data['fs_id'])) {
      $whereTj[] = ['fs_id', '=', $data['fs_id']];
    }
    $whereTj[] = ['hour_stamp', 'between', [$start_date, $end_date]];
    $fromType = '$cid';
    $hasAds = mongodb()->file_list->aggregate([
      ['$match' => $where],
      ['$group' => ['_id' => $fromType, 'count' => ['$sum' => 1]]],
      ['$sort' => ['count' => -1]],
      ['$skip' => (int)$skip],
      ['$limit' => (int)$data['pageSize']],
    ]);
    $newData = [];
    foreach ($hasAds as $document) {
      $newData[] = (array)$document;
    }
    $totalNum = Db::connect('mongodb')->name('file_list')->where($whereTj)->count();
    foreach ($newData as $key => $vo) {
      $newData[$key]['rate'] = round($vo['count'] / $totalNum * 100, 2) . '%';
    }
    $returnData['data'] = $newData;
    $returnData['totalCount'] = $totalNum;
    $returnData['pageNo'] = (int) $data['pageNo'];
    $returnData['pageSize'] = (int) $data['pageSize'];
    return Result::Success($returnData);
  }
  public function single_file_data()
  {
    $rule = [
      'date_num'  => 'require',
      'date_range'  => 'require',
    ];
    $data = [
      'date_num' => input('param.date_num', '', 'trim'),
      'from_type' => input('param.from_type', '', 'trim'),
      'date_range' => input('param.date_range_format/a', '', 'trim'),
      'fs_id' => input('param.fs_id', '', 'trim'),
      'cid' => input('param.cid', '', 'trim'),
      'email_tab' => input('param.email_tab', '', 'trim'),
      'pageNo' => input('param.pageNo', 1, 'trim'),
      'pageSize' => input('param.pageSize', 15, 'trim'),
    ];
    $validate = Validate::rule($rule);
    $result   = $validate->check($data);
    if (!$result) {
      return Result::Error($validate->getError());
    }

    $start_date = strtotime($data['date_range'][0]);
    $end_date = strtotime($data['date_range'][1]);

    $end_date = $end_date + 86399;
    if ($end_date - $start_date > 86400 * 90) {
      return Result::Error('时间跨度不能大于90天');
    }
    $where['hour_stamp'] = ['$gte' => $start_date, '$lte' => $end_date];
    $skip = ($data['pageNo'] - 1) * $data['pageSize'];

    $where['uid'] = $this->uid;
    $where['send_result'] = true;
    if (!empty($data['fs_id'])) {
      $where['fs_id'] = $data['fs_id'];
    }
    if (!empty($data['cid'])) {
      $where['cid'] = $data['cid'];
    }
    $whereTj[] = ['uid', '=', $this->uid];
    $whereTj[] = ['send_result', '=', true];
    if (!empty($data['cid'])) {
      $whereTj[] = ['cid', '=', $data['cid']];
    }
    $whereTj[] = ['hour_stamp', 'between', [$start_date, $end_date]];
    switch ($data['email_tab']) {
      case '1':
        $fromType = '$fs_id';
        break;
      case '2':
        $fromType = '$title';
        if (!empty($data['fs_id'])) {
          $whereTj[] = ['fs_id', '=', $data['fs_id']];
        }
        break;
      case '3':
        $fromType = '$title';
        if (!empty($data['fs_id'])) {
          $whereTj[] = ['fs_id', '=', $data['fs_id']];
        }
        break;
      default:
        $fromType = '$cid';
        break;
    }
    if ($data['email_tab'] == '3') {
      $where['is_read'] = 1;
      $read_count = mongodb()->file_list->count($where);
      $where['is_read'] = 0;
      $unread_count = mongodb()->file_list->count($where);
      $newData = [];
      $itemBuild['_id'] = '已读量';
      $itemBuild['count'] = $read_count;
      $newData[] = $itemBuild;
      $itemBuild['_id'] = '未读量';
      $itemBuild['count'] = $unread_count;
      $newData[] = $itemBuild;
    } else {
      $hasAds = mongodb()->file_list->aggregate([
        ['$match' => $where],
        ['$group' => ['_id' => $fromType, 'count' => ['$sum' => 1]]],
        ['$sort' => ['count' => -1]],
        ['$skip' => (int)$skip],
        ['$limit' => (int)$data['pageSize']],
      ]);
      $newData = [];
      foreach ($hasAds as $document) {
        $newData[] = (array)$document;
      }
    }

    $totalNum = Db::connect('mongodb')->name('file_list')->where($whereTj)->count();
    foreach ($newData as $key => $vo) {
      $newData[$key]['rate'] = ($totalNum == 0) ? 0 : round($vo['count'] / $totalNum * 100, 2) . '%';
    }
    $returnData['data'] = $newData;
    $returnData['totalCount'] = $totalNum;
    $returnData['pageNo'] = (int) $data['pageNo'];
    $returnData['pageSize'] = (int) $data['pageSize'];
    return Result::Success($returnData);
  }
  public static function getPlatform($platform)
  {
    $platformText = '';
    switch ($platform) {
      case 'aliyun_oss':
        $platformText = '阿里云OSS';
        break;
      case 'tencent_cos':
        $platformText = '腾讯云COS';
        break;
      case 'qiniu':
        $platformText = '七牛云';
        break;
      default:
        $platformText = '未知';
        break;
    }
    return empty($platformText) ? '未知' : $platformText;
  }
}
